<template>
 <div class="content">

   <el-dialog title="家长管理" :visible.sync="dialogVisible" width="600px" @close="closeDialog">
     <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" style="width: 100%">
         <el-form-item label="名字" prop="name"  >
           <el-input v-model="form.name" style="width: 340px" placeholder="如：张三"></el-input>
         </el-form-item>
         <el-form-item label="性别" prop="sex">
           <el-radio-group v-model="form.sex">
             <el-radio :label="1">男</el-radio>
             <el-radio :label="2">女</el-radio>
           </el-radio-group>
         </el-form-item>
         <el-form-item label="电话" prop="tel">
           <el-input v-model="form.tel" style="width: 340px" type="number"></el-input>
         </el-form-item>

<!--          动态增加项目 -->
         <el-form-item
           v-for="(student, Index) in form.studentList"
           label="孩子">
           <span style="margin-left: 15px;margin-right: 10px">学号</span>
           <el-input v-model="student.schoolno" palceholder="请输入孩子学号" style="width: 130px" type="number"></el-input>
           <span style="margin-left: 15px;margin-right: 10px">关系</span>
           <el-input v-model="student.relation" palceholder="请输入之间关系" style="width: 100px" ></el-input>
           <el-button v-if="Index!=0" type="danger" icon="el-icon-delete" circle @click.prevent="removeStudent(student)"
                      style="margin-left: 20px"></el-button>
         </el-form-item>

       <el-form-item label="照片" prop="photo">
         <el-upload
           ref="upload"
           class="avatar-uploader"
           action="http://localhost:8085/files/upload"
           :show-file-list="true"
           :on-success="handleAvatarSuccess"
           :before-upload="beforeAvatarUpload">
           <img v-if="form.photo" :src="form.photo" class="avatar">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
       </el-form-item>

       <el-form-item>
         <el-button type="success" plain @click="addStudent">新增孩子</el-button>
         <el-button type="primary" @click="handleUpdate" v-if="this.form.id">更新</el-button>
         <el-button type="primary" @click="handleSave" v-else>添加</el-button>
       </el-form-item>
     </el-form>
   </el-dialog>

   <el-form :inline="true"  class="demo-form-inline">
     <el-form-item>
       <el-input  placeholder="家长姓名" v-model="search"></el-input>
     </el-form-item>
     <el-form-item>
       <el-button  @click="getList">搜索</el-button>
     </el-form-item>
     <el-form-item>
       <el-button type="primary" @click="dialogVisible = true">添加家长</el-button>
     </el-form-item>
     <el-form-item >
       <el-form-item >
         <el-popconfirm title="这是确定批量删除吗？" @onConfirm="handleDel(null)">
           <template #reference>
             <el-button type="danger" slot="reference" :disabled="delBtlStatu">批量删除</el-button>
           </template>
         </el-popconfirm>
       </el-form-item>
     </el-form-item>
   </el-form>
   <el-table
     :data="table"
     ref="multipleTable"
     tooltip-effect="light"
     style="width: 100%;font-size: 10px"
     sroll
     border
     stripe
     @row-click="toggleSelection"
     @selection-change="handleSelectionChange"
     v-loading="loading"
     element-loading-text="拼命加载中..."
     element-loading-background="rgba(255, 255, 255, 0.7)">
     <el-table-column type="selection" width="55"></el-table-column>
     <el-table-column
       label="照片"
     >
       <template slot-scope="scope">

         <el-avatar shape="square" v-if="scope.row.photo==null||scope.row.photo===''" size="medium" :src="squareUrl"></el-avatar>
         <el-avatar shape="square" v-else size="medium" :src="scope.row.photo"></el-avatar>
       </template>
     </el-table-column>
     <el-table-column
       prop="name"
       label="姓名">
     </el-table-column>
     <el-table-column
       label="性别">
       <template slot-scope="scope">
         <p v-if="scope.row.sex===1">男</p>
         <p v-else>女</p>
       </template>
     </el-table-column>
     <el-table-column
       prop="tel"
       label="电话"
       show-overflow-tooltip
     >
     </el-table-column>
     <el-table-column
       label="操作"
       width="120"
       fixed="right">
       <template slot-scope="scope">
         <el-button  type="text" size="small" @click="handelEdit(scope.row)">编辑</el-button>
         <el-divider direction="vertical"></el-divider>
         <el-popconfirm title="这是确定删除吗？" @onConfirm="handleDel(scope.row.id)">
           <el-button  type="text" slot="reference" size="small">删除</el-button>
         </el-popconfirm>
       </template>
     </el-table-column>
   </el-table>
   <el-pagination
     @size-change="handleSizeChange"
     @current-change="handleCurrentChange"
     :current-page="current"
     :page-sizes="[5, 10, 20, 30]"
     :page-size="size"
     layout="total, sizes, prev, pager, next, jumper"
     :total="total">
   </el-pagination>
 </div>
</template>

<script>
import { getList, save ,update,del} from '@/api/sysUser/parent'

export default {
  name: "Parent",
  data(){
    return{
      dialogSutdentVisible: false,
      dialogVisible: false,
      //头像
      squareUrl:"https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      loading: true,
      //批量删除
      delBtlStatu: true,
      //表格
      table:[],
      // 分页用到的属性
      total: 0,
      current: 1,
      size: 10,
      //搜索
      search:'',
      //校验
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '请选性别', trigger: 'blur' },
        ],
        tel: [
          { required: true, message: '请填电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '长度在 11 个字符', trigger: 'blur' }
        ],
        studentList: [
          { required: true, message: '请填电话号码', trigger: 'blur' }
        ],
      },
      //表单
      form:{
        id:"",
        name:"",
        sex:"",
        tel:"",
        photo:"",
        studentList:[{
          studentId:"",
          schoolno:"",
          relation:"",
        }],
      },
      //用于校验孩子是否填写
      ruleStudentList:[{
        studentId:"",
        schoolno:"",
        relation:"",
      }],

    }
  },
  created() {
    this.getList()
  },
  methods:{
    toggleSelection(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    // 触发事件为有复选框发生变化，会传递所有勾选的行数据对象数组
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //设置批量删除的按钮的可用/不可用
      this.delBtlStatu = val.length == 0
    },
    //这里是分页
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
    },
    getList(){
      getList(this.search,this.current,this.size).then(res => {
        this.table = res.data.data.records
        this.size = res.data.data.size
        this.total = res.data.data.total
        this.current = res.data.data.current
        this.loading = false
      })
    },
    //上传
    handleAvatarSuccess(res, file) {
      this.form.photo = res.data.data
      // this.form.photo = URL.createObjectURL(file.raw);
      this.$message({
        message:"已上传成功",
        type:"success"
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //动态添加
    addStudent() {
      if (this.form.studentList === null){
        this.form.studentList = [{ schoolno:"", relation:"", }]
      }else {
        this.form.studentList.push({
          schoolno:"",
          relation:""
        })
      }


    },
    removeStudent(item) {
      var index = this.form.studentList.indexOf(item)
      if (index !== -1) {
        this.form.studentList.splice(index, 1)
      }
    },
    closeDialog(){
      this.form = { id:"", name:"", sex:"", tel:"", photo:"", studentList:[{ schoolno:"", relation:"", }], }
      this.$refs.form.resetFields()
      this.dialogVisible = false
      this.$refs.upload.clearFiles()  //清空文件
    },
    handleSave(){
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.studentList !== this.ruleStudentList){
            save(this.form).then(res => {
              this.dialogVisible = false
              this.$message({
                message: res.data.msg,
                type: 'success'
              })
              this.getList()
            })
          }else {
            this.$message({
              message: "请填写孩子信息",
              type: 'error'
            })
            return false
          }
        } else {
          return false;
        }
      });
    },
    handleUpdate(){
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.studentList !== this.ruleStudentList){
            update(this.form).then(res => {
              this.dialogVisible = false
              this.$message({
                message: res.data.msg,
                type: 'success'
              })
              this.getList()
            })
          }else {
            this.$message({
              message: "请填写孩子信息",
              type: 'error'
            })
            return false
          }
        } else {
          return false;
        }
      });
    },
    handleDel(id){
      const ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }

      del(ids).then(res => {
        this.$message({
          message: res.data.msg,
          type: 'success'
        });
        this.getList()
      })
    },
    handelEdit(row){
      this.dialogVisible = true
      this.$nextTick(() => {
        this.form = JSON.parse(JSON.stringify(row))
      })
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
